package com.crb.crm.manage.oos.local;

import com.crb.crm.manage.enums.OssType;
import com.crb.crm.manage.oos.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;

/**
 * 本地上传下载工具类
 *
 * @author simon
 * @create 2018-08-15 11:21
 **/
@Slf4j
@Component
class LocalFileUtil implements OSSUtil {

    @Resource
    private LocalOssConfig localOssConfig;

    @Override
    public OssType support() {
        return OssType.LOCAL;
    }

    @Override
    public boolean upload(InputStream is, String key) {
        try {
            int index;
            byte[] bytes = new byte[1024];
            File destinationFileDir=new File(localOssConfig.getBucket());
            if(!destinationFileDir.exists()){
                destinationFileDir.mkdirs();
            }
            String destination = localOssConfig.getBucket().concat(key);
            FileOutputStream localFile = new FileOutputStream(destination);
            while ((index = is.read(bytes)) != -1) {
                localFile.write(bytes, 0, index);
                localFile.flush();
            }
            is.close();
            localFile.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean delete(String key) {
        File file = new File(localOssConfig.getBucket().concat(key));
        return file.delete();
    }

    @Override
    public InputStream download(String key) throws FileNotFoundException {
        return new FileInputStream(localOssConfig.getBucket().concat(key));
    }
}